//
//  SCRNManager+Message.m
//  Shuaiche
//
//  Created by xiangtao on 2024/12/19.
//  Copyright © 2024 ShuaiChe. All rights reserved.
//

#import "SCRNManager+Message.h"
//#import "SCCarDetailVC.h"
//#import "SCOrderDetailViewController.h"
//#import "SCCompanyDetailVc.h"
//#import "SCPurchaseChooseCarVc.h"
#import "MJPhotoBrowser.h"
#import "CDPAudioRecorder.h"
#import "GSVoicePlayer.h"
#import "SCRNEventManager.h"
#import <AliyunOSSiOS/OSSService.h>
#import <AliyunOSSiOS/OSSCompat.h>
#import "SCIMUploadManager.h"
//#import "SCMemberTreeVC.h"
//#import "TreeItem.h"
#import "Config.h"


static NSString *const endPoint = @"https://oss-cn-hangzhou.aliyuncs.com";
static NSString *const bucketName = @"imgrep";
static NSString *const kAccessKeyId = @"accessKeyId";
static NSString *const kAccessKeySecret = @"accessKeySecret";
static NSString *const kSecurityToken = @"securityToken";
static NSString *const kExpiration = @"expiration";


@interface SCRNManager ()<CDPAudioRecorderDelegate, UIDocumentPickerDelegate>

@property (strong, nonatomic) UIDocumentPickerViewController *documentPickerVC;


@end

@implementation SCRNManager (Message)

//车辆详情
RCT_EXPORT_METHOD(goCarDetail:(NSString *)carId merchantId:(NSString *)merchantId)
{
    dispatch_async(dispatch_get_main_queue(), ^(){
//        SCCarDetailVC *detailVC = [[SCCarDetailVC alloc] init];
//        detailVC.carId = carId;
//        detailVC.merchantId = merchantId.intValue;
//        [[self getCurrentVC].navigationController pushViewController:detailVC animated:YES];
    });
}

//订单详情
RCT_EXPORT_METHOD(goOrderDetail:(NSString *)orderNo orderType:(int)orderType)
{
    dispatch_async(dispatch_get_main_queue(), ^(){
//        SCOrderDetailViewController *order = [[SCOrderDetailViewController alloc] init];
//        order.orderNo = orderNo;
//        order.orderType = orderType;
//        [[self getCurrentVC].navigationController pushViewController:order animated:YES];
    });
}

//商家详情
RCT_EXPORT_METHOD(goCompanyDetail:(NSString *)merchantId)
{
    dispatch_async(dispatch_get_main_queue(), ^(){
//        SCCompanyDetailVc *detail = [[SCCompanyDetailVc alloc] init];
//        detail.merchantId = merchantId.intValue;
//        [[self getCurrentVC].navigationController pushViewController:detail animated:YES];
    });
}

//图片预览
RCT_EXPORT_METHOD(imagePreview:(NSDictionary *)params)
{
    dispatch_async(dispatch_get_main_queue(), ^(){
        NSArray *imgList = [params objectForKey:@"imgList" matchClass:[NSArray class] defaultValue:nil];
        NSMutableArray *marray = [NSMutableArray arrayWithCapacity:0];
        MJPhotoBrowser *photoBrowser = [[MJPhotoBrowser alloc] init];
        for (NSString *str in imgList) {
            MJPhoto *photo = [[MJPhoto alloc] init];
            photo.url = [NSURL URLWithString:sc_url_img(str)];
            [marray addObject:photo];
        }
        photoBrowser.photos = marray;
        photoBrowser.showSaveBtn = YES;
        photoBrowser.currentPhotoIndex = 0;
        [photoBrowser show];
    });
}

//选择车辆
RCT_EXPORT_METHOD(selectCar:(NSDictionary *)params)
{
    dispatch_async(dispatch_get_main_queue(), ^(){
        NSString *type = [params objectForKey:@"type" defaultValue:nil];
        
//        SCPurchaseChooseCarVc *cars = [[SCPurchaseChooseCarVc alloc] init];
//        if ([type isEqualToString:@"1"]) {//消息选择车辆
//            NSString *merchantId = [params objectForKey:@"merchantId" defaultValue:nil];
//            NSString *merchantAbbreviation = [params objectForKey:@"merchantAbbreviation" defaultValue:nil];
//            SCParamModel *params = [[SCParamModel alloc] initWithEntranceType:SCCarEntranceTypeAllCar];
//            [params.disPlayParams setValue:merchantAbbreviation forKey:kMerchantAbbreviation];
//            [params.uploadParams setValue:@"2,3" forKey:kSaleStatus];
//            [params.uploadParams setValue:@[merchantId] forKey:kMerchantIds];
//            cars.paramModel = params;
//        } else if ([type isEqualToString:@"2"]) {//合同选择车辆
//            SCParamModel *params = [[SCParamModel alloc] initWithEntranceType:SCCarEntranceTypeInStore];
//            [params.uploadParams setValue:@"2,3" forKey:kSaleStatus];
//            [params.uploadParams setValue:@([Config sharedConfig].user.merchantId) forKey:kMerchantId];
//            cars.paramModel = params;
//        }
//        
//        cars.didSelectCar = ^(SCCarBaseModel * _Nonnull car) {
//            NSLog(@"car = %@",[car yy_modelToJSONObject]);
//            NSDictionary *carInfo = @{
//                @"carId": car.carId,
//                @"carTitle": [NSString stringWithFormat:@"%@%@",car.seriesName,car.speciesName],
//                @"carPrice": [NSString stringWithFormat:@"%.2f万",[car.markedPrice integerValue]/10000.],
//                @"mainPic": car.mainPic,
//                @"merchantId": @(car.merchantId),
//                @"mile": [NSString stringWithFormat:@"%.2f万公里",[car.mileage integerValue]/10000.],
//                @"registerDate": car.registerDate ? car.registerDate:@"",
//                @"Vcode": car.vcode ? car.vcode:@""
//            };
//            [[SCRNEventManagerContainer shareInstance] selectCarResultListener: carInfo];
//        };;
//        [[self getCurrentVC].navigationController pushViewController:cars animated:YES];
    });
}

//选择公司
RCT_EXPORT_METHOD(selectCompany:(NSDictionary *)params)
{
    dispatch_async(dispatch_get_main_queue(), ^(){
//        SCMemberTreeVC *memberTreeVC = [[SCMemberTreeVC alloc] init];
//        memberTreeVC.isSingleSelect = YES;
//        WEAKSELF
//        memberTreeVC.completion = ^(NSArray *allItems) {
//            if (allItems.count > 0) {
//                TreeItem *item = allItems[0];
//                NSDictionary *dic = [item yy_modelToJSONObject];
//                NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:[dic objectForKey:@"memer" matchClass:[NSDictionary class] defaultValue:nil]];
//                params[@"type"] = @"selectCompanyResult";
//                [[SCRNEventManagerContainer shareInstance] commonEvent:params];
//            }
//        };
//        [[self getCurrentVC].navigationController pushViewController:memberTreeVC animated:YES];
    });
}

//选择文件
RCT_EXPORT_METHOD(selectLocalFile:(NSDictionary *)params)
{
    dispatch_async(dispatch_get_main_queue(), ^(){
        NSString *fileType = [params objectForKey:@"fileType" defaultValue:nil];
        if ([fileType isEqualToString:@"image"]) {
            uploadType = UploadTypeIMImageOrVideo;
            [self pickPhotoFromAlbumAndUpload:1];
        } else {
            if (@available(iOS 11.0, *)) {
                UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAutomatic;
            }
            
//            NSArray * types = @[@"com.adobe.pdf",@"com.microsoft.word.docx"];
            NSArray*types = @[
                @"public.data",
                @"com.microsoft.powerpoint.ppt",
                @"com.microsoft.word.doc",
                @"com.microsoft.excel.xls",
                @"com.microsoft.powerpoint.pptx",
                @"com.microsoft.word.docx",
                @"com.microsoft.excel.xlsx",
                @"public.avi",
                @"public.3gpp",
                @"public.mpeg-4",
                @"com.compuserve.gif",
                @"public.jpeg",
                @"public.png",
                @"public.plain-text",
                @"com.adobe.pdf"
            ];
            
            UIDocumentPickerViewController *documentPickerVC = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:types inMode:UIDocumentPickerModeOpen];
            documentPickerVC.edgesForExtendedLayout = UIRectEdgeNone;
            //设置代理
            documentPickerVC.delegate = self;
            //设置模态弹出方式
            documentPickerVC.modalPresentationStyle = UIModalPresentationFullScreen;
            
            [[self getCurrentVC] presentViewController:documentPickerVC animated:YES completion:nil];
        }
    });
}

RCT_EXPORT_METHOD(testAudioRecord)
{
    dispatch_async(dispatch_get_main_queue(), ^(){
//        [CDPAudioRecorder getAudioRecordFilePathWithMark:NO];
        // 初始化录音recorder
        CDPAudioRecorder *recorder = [CDPAudioRecorder shareRecorder];
        recorder.delegate = self;
        [recorder startRecording];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [recorder stopRecording];
        });
    });
}

//开始音频录制
RCT_EXPORT_METHOD(startAudioRecord)
{
    dispatch_async(dispatch_get_main_queue(), ^(){
//        [CDPAudioRecorder getAudioRecordFilePathWithMark:NO];
        // 初始化录音recorder
        if ([self audioAuthority]) {
            CDPAudioRecorder *recorder = [CDPAudioRecorder shareRecorder];
            recorder.delegate = self;
            [recorder startRecording];
        }
    });
}

//停止音频录制
RCT_EXPORT_METHOD(stopAudioRecord)
{
    dispatch_async(dispatch_get_main_queue(), ^(){
        CDPAudioRecorder *recorder = [CDPAudioRecorder shareRecorder];
        [recorder stopRecording];
    });
}

//播放网络音频
RCT_EXPORT_METHOD(palyAudio:(NSString *)url)
{
    dispatch_async(dispatch_get_main_queue(), ^(){
        if (url) {
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(PlayFinishedNotification:) name:@"PlayFinishedNotification" object:nil];
            GSVoicePlayer *player = [GSVoicePlayer sharedVoicePlayerMethod];
            [player playWithFilePath:url];
        }
    });
}

//播放本地音频
RCT_EXPORT_METHOD(palyLocalAudio)
{
    dispatch_async(dispatch_get_main_queue(), ^(){
        if (localAudioPathUrl) {
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(PlayFinishedNotification:) name:@"PlayFinishedNotification" object:nil];
            GSVoicePlayer *player = [GSVoicePlayer sharedVoicePlayerMethod];
            [player playWithFilePath:localAudioPathUrl];
        }
    });
}

//停止播放音频
RCT_EXPORT_METHOD(stopAudio)
{
    dispatch_async(dispatch_get_main_queue(), ^(){
        GSVoicePlayer *player = [GSVoicePlayer sharedVoicePlayerMethod];
        [player stopVoice];
    });
}

//获取音频时长
RCT_EXPORT_METHOD(getAudioDuration:(NSString *)url callback:(RCTResponseSenderBlock)callback)
{
    NSInteger duration = 0;
    if (url) {
        duration = [GSVoicePlayer audioDurationFromURL:url];
    }
    dispatch_async(dispatch_get_main_queue(), ^(){
        callback(@[@(duration)]);
    });
}

//上传音频
RCT_EXPORT_METHOD(uploadAudio)
{
    dispatch_async(dispatch_get_main_queue(), ^(){
        AVAuthorizationStatus statusAudio = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
        if (statusAudio == AVAuthorizationStatusDenied) {
            return;
        }
        NSString *filePath = localAudioPathUrl;
        NSData *voiceData = [NSData dataWithContentsOfFile:filePath];
        NSLog(@"voiceData = %ld",voiceData.length);
        MBProgressHUD *hud = [MBProgressHUD showMessage:@"正在转码" toView:[self getCurrentVC].view];
        if (voiceData) {
            // 异步caf转MP3
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                [GSVoicePlayer transformCAFToMP3:[NSURL URLWithString:filePath] Success:^(NSInteger mark) {
                    dispatch_async(dispatch_get_main_queue(), ^(){
                        if (mark) {
                            [hud hide:YES];
                            [self dealFileAction];
                        } else {
                            [hud switchShowError:@"转码失败"];
                        }
                    });
                }];
            });
        } else {
            [hud switchShowError:@"语音输入失败"];
            NSDictionary *params = @{
                @"errorMsg": @"语音输入失败",
            };
            [[SCRNEventManager shareInstance] uploadAudioFailed:params];
        }
    });
}

#pragma mark - CDPAudioRecorderDelegate代理事件
// 更新音量分贝数峰值(0~1)
- (void)updateVolumeMeters:(CGFloat)value {
    NSInteger no = 0;
    if (value>0 && value<=0.14) {
        no = 1;
    } else if (value <= 0.28) {
        no = 2;
    } else if (value <= 0.42) {
        no = 3;
    } else if (value <= 0.56) {
        no = 4;
    } else if (value <= 0.7) {
        no = 5;
    } else if (value <= 0.84) {
        no = 6;
    } else{
        no = 7;
    }
    //    LogInfo(@"no = %ld",no);
}

// 录音结束(url为录音文件地址,isSuccess是否录音成功)
- (void)recordFinishWithUrl:(NSString *)url isSuccess:(BOOL)isSuccess {
    // url为得到的caf录音文件地址,可直接进行播放,也可进行转码为amr、mp3上传服务器
    NSLog(@"录音完成,文件地址:%@",url);
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [path stringByAppendingPathComponent:@"CDPAudioFiles/CDPAudioRecord.caf"];
    NSLog(@"filePath = %@",filePath);
    NSTimeInterval time = [GSVoicePlayer audioDurationFromURL:filePath];
    NSLog(@"time = %lf",time);
    localAudioPathUrl = filePath;
}

// 转换格式成功后 上传
- (void)dealFileAction {
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [path stringByAppendingPathComponent:@"CDPAudioFiles/CDPAudioRecord.mp3"];
    NSLog(@"filePath = %@",filePath);
    NSInteger duration = [GSVoicePlayer audioDurationFromURL:filePath];
    NSData *voiceData = [NSData dataWithContentsOfFile:filePath];
    if (duration <= 0 || voiceData.length <= 0) {
        [MBProgressHUD showError:@"语音输入失败，请重新录入." toView:[self getCurrentVC].view];
        NSDictionary *params = @{
            @"errorMsg": @"语音输入失败",
        };
        [[SCRNEventManager shareInstance] uploadAudioFailed:params];
        return;
    }
    
    [SCIMUploadManager startUploadVoice:voiceData completion:^(NSString *voiceUrl,NSString *errorString){
        NSLog(@"voiceUrl = %@",voiceUrl);
        if (voiceUrl) {
            NSDictionary *params = @{
                @"url": voiceUrl,
                @"second": [NSString stringWithFormat:@"%ld",duration]
            };
            NSLog(@"params = %@",params);
            [[SCRNEventManager shareInstance] uploadAudioFinish:params];
        }
    }];
}

// 结束播放通知
- (void)PlayFinishedNotification:(id)sender {
    dispatch_async(dispatch_get_main_queue(), ^{
        [[SCRNEventManager shareInstance] playAudioFinish];
    });
}

#pragma mark - UIDocumentPickerDelegate

- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls {
    //获取授权
    BOOL fileUrlAuthozied = [urls.firstObject startAccessingSecurityScopedResource];
    if (fileUrlAuthozied) {
        //通过文件协调工具来得到新的文件地址，以此得到文件保护功能
        NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
        NSError *error;

        [fileCoordinator coordinateReadingItemAtURL:urls.firstObject options:0 error:&error byAccessor:^(NSURL *newURL) {
            //读取文件
            NSString *fileName = [newURL lastPathComponent];
            NSError *error = nil;
            NSData *fileData = [NSData dataWithContentsOfURL:newURL options:NSDataReadingMappedIfSafe error:&error];
            NSLog(@"fileName = %@, fileData.length = %ld",fileName,fileData.length);
            NSThread *thread = [NSThread currentThread];
            NSLog(@"thread = %@",thread);
            
            [SCIMUploadManager startUploadFile:fileData fileName:fileName completion:^(NSString *fileUrl, NSString *errorString){
                NSLog(@"fileUrl = %@",fileUrl);
                if (fileUrl) {
                    NSDictionary *params = @{
                        @"fileOssPath": fileUrl,
                        @"fileName": fileName
                    };
                    NSLog(@"params = %@",params);
                    [[SCRNEventManager shareInstance] uploadIMSuccess:params];
                }
            }];
            
            if (error) {
                //读取出错
            } else {
                
            }
            [[self getCurrentVC] dismissViewControllerAnimated:YES completion:NULL];
        }];
        [urls.firstObject stopAccessingSecurityScopedResource];
    } else {
        //授权失败
    }
    if (@available(iOS 11.0, *)) {
        UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
}

- (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller{
    if (@available(iOS 11.0, *)) {
        UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
}

- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url{
    if (@available(iOS 11.0, *)) {
        UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
}

- (BOOL)audioAuthority
{
    AVAuthorizationStatus statusAudio = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    if(statusAudio == AVAuthorizationStatusDenied){
        // The user has explicitly denied permission for media capture.
        [UIAlertController showAlertInViewController:ROOT_VC withTitle:@"提示" message:@"请在iPhone的\"设置-隐私\"选项中，允许帅车内采访问你的麦克风，才能使用该功能。" cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@[@"去设置"] tapBlock:^(UIAlertController *controller, UIAlertAction *action, NSInteger buttonIndex){
            if (buttonIndex != controller.cancelButtonIndex) {
                NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                [[UIApplication sharedApplication] openURL:url options:nil completionHandler:nil];
            }
        }];
        return NO;
    }
    return YES;
}

@end
